package com.auto.learning.tools;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.auto.learning.R;
import com.auto.learning.bean.ImageItem;
import com.auto.learning.view.TouchImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class ImagePopWindowUtils {

	private static final String TAG = "PhotoViewer";
	public static final int RESULT_CODE_NOFOUND = 200;
	

	RelativeLayout linar_main;

	/** 最小缩放比例 */
	float minScaleR = 1.0f;
	/** 最大缩放比例 */
	static final float MAX_SCALE = 10f;

	/** 初始状态 */
	static final int NONE = 0;
	/** 拖动 */
	static final int DRAG = 1;
	/** 缩放 */
	static final int ZOOM = 2;

	/** 当前模式 */
	int mode = NONE;

	PointF prev = new PointF();
	PointF mid = new PointF();
	float dist = 1f;

	private Context context;
	DisplayMetrics dm;
	private PopupWindow popupWindow;
	ViewPager viewPager;
	MyPageAdapter adapter;
	
	private int currentPosition = 0;
	private ArrayList<ImageItem> imageItems;
	private LinearLayout linear_ads_indicator;
	
	public ImagePopWindowUtils(ArrayList<ImageItem> imageItems, int currentPosition, Context context, DisplayMetrics dm) {
		this.context = context;
		this.dm = dm;
		this.currentPosition = currentPosition;
		this.imageItems = imageItems;
	}

	public PopupWindow getPopupWindow() {
		View popupWindow_view = LayoutInflater.from(context).inflate(R.layout.image_zoom_pop, null, false);
		linar_main = (RelativeLayout) popupWindow_view.findViewById(R.id.linar_main);
		linar_main.setBackgroundColor(context.getResources().getColor(R.color.black));
		linear_ads_indicator = (LinearLayout) popupWindow_view.findViewById(R.id.linear_ads_indicator);
		linar_main.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (popupWindow != null && popupWindow.isShowing()) {
					popupWindow.dismiss();
					popupWindow = null;
				}
			}
		});
		
		viewPager = (ViewPager) popupWindow_view.findViewById(R.id.viewpager);
		if (imageItems.size() > 1) {
			linear_ads_indicator.setVisibility(View.VISIBLE);
			ImageView[] imageViews = new ImageView[imageItems.size()];
			Drawable imageDrawable = context.getResources().getDrawable(R.drawable.pagectr_active);
			int width = (int) (imageDrawable.getMinimumWidth() / 1.2);
			int height = (int) (imageDrawable.getMinimumHeight() / 1.2);
			for (int i = 0; i < imageViews.length; i++) {
				ImageView imageView = new ImageView(context);
				LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, height);
				lp.leftMargin = 5;
				lp.rightMargin = 5;
				imageView.setLayoutParams(lp);
				imageViews[i] = imageView;
				if (i == 0) {
					imageViews[i].setBackgroundResource(R.drawable.page_select);
				} else {
					imageViews[i].setBackgroundResource(R.drawable.page_unselect);
				}
				linear_ads_indicator.addView(imageViews[i]);
			}
			viewPager.setOnPageChangeListener(new GuidePageChangeListener(imageViews));
		}else {
			linear_ads_indicator.setVisibility(View.GONE);
			viewPager.setOnPageChangeListener(pageChangeListener);
		}
		adapter = new MyPageAdapter(imageItems);
		viewPager.setAdapter(adapter);
		viewPager.setCurrentItem(currentPosition);
		popupWindow = new PopupWindow(popupWindow_view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow_view.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (popupWindow != null && popupWindow.isShowing()) {
					popupWindow.dismiss();
					popupWindow = null;
				}
				return false;
			}
		});
		popupWindow.setOutsideTouchable(true);
		popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
		return popupWindow;
	}
	
	private class GuidePageChangeListener implements OnPageChangeListener {

		private ImageView[] imageViews;

		public GuidePageChangeListener(ImageView[] imageViews) {
			this.imageViews = imageViews;
		}

		public void onPageScrollStateChanged(int arg0) {

		}

		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

		}

		public void onPageSelected(int position) {
			currentPosition = position;
			for (int i = 0; i < imageViews.length; i++) {
				if (position != i) {
					imageViews[i].setBackgroundResource(R.drawable.page_unselect);
				}else {
					imageViews[position].setBackgroundResource(R.drawable.page_select);
				}
			}
		}
	}
	
	private OnPageChangeListener pageChangeListener = new OnPageChangeListener(){

		public void onPageSelected(int arg0){
			currentPosition = arg0;
		}

		public void onPageScrolled(int arg0, float arg1, int arg2){
			
		}

		public void onPageScrollStateChanged(int arg0){

		}
	};

	public void SureOnClick(View v) {

	}


	private Matrix center(TouchImageView imgView, Bitmap bitmap) {
		return center(imgView, bitmap, true, true);
	}

	/**
	 * 横向、纵向居中
	 */
	protected Matrix center(TouchImageView imgView, Bitmap bitmap, boolean horizontal, boolean vertical) {

		Matrix matrix = new Matrix();
		RectF rect = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
		matrix.mapRect(rect);

		float height = rect.height();
		float width = rect.width();

		float deltaX = 0, deltaY = 0;

		if (vertical) {
			// 图片小于屏幕大小，则居中显示。大于屏幕，上方留空则往上移，下方留空则往下移
			int screenHeight = dm.heightPixels;
			if (height < screenHeight) {
				deltaY = (screenHeight - height) / 2 - rect.top;
			} else if (rect.top > 0) {
				deltaY = -rect.top;
			} else if (rect.bottom < screenHeight) {
				deltaY = imgView.getHeight() - rect.bottom;
			}
		}

		if (horizontal) {
			int screenWidth = dm.widthPixels;
			if (width < screenWidth) {
				deltaX = (screenWidth - width) / 2 - rect.left;
			} else if (rect.left > 0) {
				deltaX = -rect.left;
			} else if (rect.right < screenWidth) {
				deltaX = screenWidth - rect.right;
			}
		}
		matrix.postTranslate(deltaX, deltaY);
		return matrix;
	}

	
	class MyPageAdapter extends PagerAdapter{
		private List<ImageItem> dataList = new ArrayList<ImageItem>();
		private ArrayList<TouchImageView> mViews = new ArrayList<TouchImageView>();

		public MyPageAdapter(List<ImageItem> dataList){
			this.dataList = dataList;
			int size = dataList.size();
			for (int i = 0; i != size; i++){
				if (!TextUtils.isEmpty(imageItems.get(i).sourcePath)) {
					final TouchImageView imgView = new TouchImageView(context);// 获取控件
					imgView.setScaleType(ScaleType.MATRIX);
					imgView.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							if (popupWindow != null && popupWindow.isShowing()) {
								popupWindow.dismiss();
								popupWindow = null;
							}
						}
					});
					mViews.add(imgView);
					ImageLoader.getInstance().loadImage(imageItems.get(i).sourcePath, new ImageSize(480, 800), new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String arg0, View arg1, Bitmap bitmap) {
							imgView.setImageBitmap(bitmap);			// 填充控件
							imgView.setImageMatrix(center(imgView, bitmap));
						}
					});
				}
			}
		}

		public int getItemPosition(Object object){
			return POSITION_NONE;
		}

		public Object instantiateItem(View arg0, int arg1){
			ImageView iv = mViews.get(arg1);
			((ViewPager) arg0).addView(iv);
			return iv;
		}

		public void destroyItem(View arg0, int arg1, Object arg2){
			if (mViews.size() >= arg1 + 1){
				((ViewPager) arg0).removeView(mViews.get(arg1));
			}
		}

		public boolean isViewFromObject(View arg0, Object arg1){
			return arg0 == arg1;
		}

		@Override
		public int getCount(){
			return dataList.size();
		}

		public void removeView(int position){
			if (position + 1 <= mViews.size()){
				mViews.remove(position);
			}
		}
	}
}
